﻿using System;
using System.Security.Principal;
using System.Web;
using KL.UFrame.Core.Log;
using KL.UFrame.Core.Unity;

namespace KL.UFrame.Core.Exception
{
    public static class ApplicationError
    {
        private static ICommonLogger _logger;

        static ApplicationError()
        {
            _logger = UnityBootstrapper.Current.GetService<ICommonLogger>();
        }
        public static void Log(HttpServerUtility server, HttpRequest request, HttpResponse response, IPrincipal user)
        {
            var lastError = server.GetLastError();
            if (lastError != null)
            {
                var httpError = lastError as HttpException;
                if (httpError != null)
                {
                    //ASP.NET的400与404错误不记录日志，并都以自定义404页面响应
                    var httpCode = httpError.GetHttpCode();
                    if (httpCode == 400 || httpCode == 404)
                    {
                        response.StatusCode = 404; //在IIS中配置自定义404页面
                        server.ClearError();
                        return;
                    }
                }

                //对于路径错误不记录日志，并都以自定义404页面响应
                if (lastError.TargetSite.ReflectedType == typeof(System.IO.Path))
                {
                    response.StatusCode = 404;
                    server.ClearError();
                    return;
                }

                response.StatusCode = 500;

                server.ClearError();

                _logger.Error("Application_Error:" + response.StatusCode
                                 + Environment.NewLine + "Url:" + HttpContext.Current.Request.Url
                                 + Environment.NewLine + "Http Method:" + HttpContext.Current.Request.HttpMethod
                                 + Environment.NewLine + "user:" + (user?.Identity?.Name??"未登录")
                                 + Environment.NewLine + "IP:" + HttpContext.Current.Request.UserHostAddress
                  , lastError);
            }
        } 
    }
}